<script>
import { getUserByIdAjax, updatePassword } from '@/data/UserinfoData'

export default {
  name: 'UserinfoPassword',
  data () {
    return {
      show: false,
      formData: { },
      loginInfo: {},
      rules: {
        oldPassword: [
          { required: true, message: '原密码不能为空' },
          {
            validator: (rule, value, callback) => {
              if (value === this.loginInfo.password) {
                callback()
              } else {
                callback(new Error('原密码不正确'))
              }
            }
          }
        ],
        password: [
          {
            required: true, message: '新密码不能为空'
          }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空' },
          {
            validator: (rule, value, callback) => {
              if (value === this.formData.password) {
                callback()
              } else {
                callback(new Error('两次密码不一致'))
              }
            }
          }
        ]
      },
      roleList: []
    }
  },
  methods: {
    getLoginInfo () {
      this.show = true
      const id = JSON.parse(sessionStorage.getItem('loginInfo'))?.id
      const res = getUserByIdAjax(id)
      if (res.code === 200) {
        this.loginInfo = { ...res.data }
      } else {
        this.$alert(res.msg, { type: 'error' })
      }
    },
    submit () {
      this.$refs.formData.validate(valid => {
        if (valid) {
          const res = updatePassword({
            id: this.loginInfo.id,
            password: this.formData.password
          })
          if (res.code === 200) {
            this.$alert('密码修改成功，请重新登录！', { type: 'success' }).then(() => {
              sessionStorage.removeItem('loginInfo')
              this.$router.replace('/')
            })
          } else {
            this.$alert(res.msg, { type: 'error' })
          }
        }
      })
    }
  }
}
</script>

<template>
<el-dialog v-if="show" :visible.sync="show" title="修改密码">
<el-form ref="formData" :model="formData" :rules="rules" label-width="80px">
  <el-form-item label="用户名">
    <el-input disabled v-model="loginInfo.username" placeholder="请输入用户名"/>
  </el-form-item>
  <el-form-item label="原密码" prop="oldPassword">
    <el-input v-model="formData.oldPassword" show-password placeholder="请输入原密码"/>
  </el-form-item>
  <el-form-item label="新密码" prop="password">
    <el-input v-model="formData.password" show-password placeholder="请输入新密码"/>
  </el-form-item>
  <el-form-item label="确认密码" prop="confirmPassword">
    <el-input v-model="formData.confirmPassword" show-password placeholder="请在此输入新密码"/>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submit">提交</el-button>
  </el-form-item>
</el-form>
</el-dialog>
</template>

<style scoped>

</style>
